import { Router, RouteRecordRaw } from 'vue-router'
const whiteList = ['/login'] //
import { AppModule } from '@/store/modules/app'
import { clone, equals, filter, forEach, isEmpty, isNil, map } from 'ramda'
import { notification } from 'ant-design-vue'
import { PermissionModule } from '@/store/modules/permission'
import { isTrue } from '@/utils/tools'
export default function (router: Router) {
	router.beforeEach(async (to, from, next: any) => {
		//  判断登录
		const hasToken = localStorage.getItem('accessToken')
		if (!hasToken) {
			if (whiteList.indexOf(to.path) !== -1) {
				next()
			} else {
				location.href = `/login?redirect=${to.path}`
			}
		} else {
			if (to.path === '/login') {
				next({ path: '/' })
			} else {
				let data
				if (!isTrue(AppModule.userInfo)) {
					data = await AppModule.getUserInfo()
				} else {
					data = AppModule.userInfo
				}
				if (isNil(data)) {
					// 去 403
					notification.error({
						description: '没有查询到用户信息',
						message: '异常',
					})
					localStorage.removeItem('accessToken')
					localStorage.removeItem('userId')
					location.href = `/login?redirect=${to.path}`
					return
				}
				// 拉取用户菜单
				const notHasRoles = isEmpty(PermissionModule.dynamicRoutes)
				// 没有菜单 去查询
				if (notHasRoles) {
					const accessRoutes = await PermissionModule.GenerateRoutes()
					if (isNil(accessRoutes) || isEmpty(accessRoutes)) {
						// 没有权限
						notification.error({
							description: '没有配置后端权限',
							message: '异常',
						})
						setTimeout(() => {
							localStorage.removeItem('accessToken')
							localStorage.removeItem('userId')
							location.href = `/login?redirect=${to.path}`
						}, 1000);
						return
					}

					forEach(router.addRoute, hdAccessRoutes(clone(accessRoutes)))
					next({ ...to, replace: true })
					return
				}
				next()
			}
		}
	})
}

/**
 * 把两级以上的嵌套路由给拍平成两级
 * @param accessRoutes
 */
function hdAccessRoutes(accessRoutes: RouteRecordRaw[]) {
	return map((item) => {
		if (isNil(item.children) || isEmpty(item.children)) {
			return item
		}
		forEach((res) => {
			if (item.children) {
				// 好家伙 这就是 二级以上的嵌套路由
				item.children = setChildren(item.children, res)
			}
		}, item.children)
		return item
	}, accessRoutes)
}

function setChildren(accessRoutes: RouteRecordRaw[], childrenAaccess: RouteRecordRaw) {
	if (childrenAaccess.children) {
		forEach((item) => {
			if (item.children) {
				// 好家伙 解决无限套娃问题
				setChildren(accessRoutes, item)
			} else {
				if (!item.path.startsWith('/')) {
					item.path = `${childrenAaccess.path}/${item.path}`
				}
				accessRoutes.push(item)
			}
		}, childrenAaccess.children)
		// 干掉嵌套的本身 加了一个限制 多次嵌套的本身 不能有component
		accessRoutes = filter((item) => !equals(item.name, childrenAaccess.name) && !isNil(item.component), accessRoutes)
	}
	return accessRoutes
}
